use serde::Deserialize;
use thiserror::Error;

/// Binance 服务器返回的标准 API 错误结构
#[derive(Debug, Clone, Deserialize)]
pub struct BinanceApiErrorResponse {
    pub code: i64,
    pub msg: String,
}

impl std::fmt::Display for BinanceApiErrorResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Binance API Error code {}: {}", self.code, self.msg)
    }
}

impl std::error::Error for BinanceApiErrorResponse {}

#[derive(Error, Debug)]
pub enum BinanceError {
    #[error("HTTP request failed: {0}")]
    RequestError(#[from] reqwest::Error),

    #[error("Serde JSON 序列化/反序列化错误: {0}")]
    SerdeError(#[from] serde_json::Error),

    #[error("URL编码错误: {0}")]
    UrlEncodeError(#[from] serde_urlencoded::ser::Error),

    #[error("WebSocket 错误: {0}")]
    WsError(#[from] tungstenite::Error),

    #[error("URL 解析错误: {0}")]
    UrlParseError(#[from] url::ParseError),

    #[error("IO 错误: {0}")]
    IoError(#[from] std::io::Error),

    #[error("TLS 错误: {0}")]
    TlsError(#[from] native_tls::Error),

    #[error("HTTP 构建错误: {0}")]
    HttpBuilderError(#[from] http::Error),

    /// 新增 ApiError，包含错误码和消息
    #[error("{0}")]
    ApiError(#[from] BinanceApiErrorResponse),

    #[error("其他错误: {0}")]
    Other(String),
}

pub type Result<T> = std::result::Result<T, BinanceError>;
